#include "CService.h"


static const unsigned char pchIPv4[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff };

void CNetAddr::Init()
{
	memset(ip, 0, sizeof(ip));
}

CNetAddr::CNetAddr()
{
	Init();
}


CNetAddr::CNetAddr(const struct in_addr& ipv4Addr)
{
	memcpy(ip,    pchIPv4,  12);
	memcpy(ip+12, &ipv4Addr, 4);
}

bool CNetAddr::GetInAddr(struct in_addr* pipv4Addr) const
{
	memcpy(pipv4Addr, ip+12, 4);
	return true;
}



bool CNetAddr::SetSpecial(const std::string &strName)
{
	if(strName.size()>6 && strName.substr(strName.size()-6, 6) == ".onion")
	{
		//TODO onion
		return true;
	}
	return false;
}

void CService::Init()
{
	port = 0;
}

CService::CService()
{
	Init();
}

CService::CService(const CNetAddr& cip, unsigned short portIn) : CNetAddr(cip),port(portIn)
{

}

CService::CService(const struct in_addr& ipv4Addr, unsigned short portIn) : CNetAddr(ipv4Addr), port(portIn)
{
}


CService::CService(const char *pszIpPort, int portDefault ,bool fAllowLookup)
{
	Init();
	
	unsigned long IpAddress = inet_addr(pszIpPort);
	struct in_addr addr;
	addr.s_addr = IpAddress;
	CService ip(addr, portDefault);
	*this = ip;
}

CService::CService(const std::string& strIpPort,int portDefault, bool fAllowLookup)
{
	Init();
	
	unsigned long IpAddress = inet_addr(strIpPort.c_str());
	struct in_addr addr;
	addr.s_addr = IpAddress;
	CService ip(addr, portDefault);
	*this = ip;
}

bool CService::GetSockAddr(struct sockaddr* paddr,int *addrlen) const
{
	if(*addrlen < (int)sizeof(struct sockaddr_in))
	 return false;
	*addrlen = sizeof(struct sockaddr_in);
	struct sockaddr_in *paddrin =(struct sockaddr_in*)paddr;
	memset(paddrin, 0, *addrlen);
	if(!GetInAddr(&paddrin->sin_addr))
		return false;
	paddrin->sin_family = AF_INET;
	paddrin->sin_port = htons(port);
	return true;
}
